package tp01.ui;

import tp01.utilitarios.ByteAndConversionsUtils;
import tp01.ConnectionController;
import tp01.Funcion03RequestCommand;
import tp01.Funcion16RequestCommand;
import tp01.Funcion6RequestCommand;
import tp01.RequestCommand;
import tp01.SerialConnectionController;
import tp01.TCPConnectionController;

public class PantallaPrincipalUI extends javax.swing.JFrame implements Interesado {

    /** Creates new form PantallaPrincipalUI */
    public PantallaPrincipalUI() {

        initComponents();

        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        Observador.getInstance().registrarInteresado(this);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldTimeOut = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldCantidadDeReintentos = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        idDispositivoJTextField = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jComboBoxFuncion = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        jTextFieldDireccionInicial = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTextFieldCantidadDeVariables = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jTextFieldValor = new javax.swing.JTextField();
        jPanel4 = new javax.swing.JPanel();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jToolBar1 = new javax.swing.JToolBar();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 679, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 327, Short.MAX_VALUE)
        );

        jSplitPane1.setRightComponent(jPanel2);

        jPanel1.setLayout(new java.awt.GridLayout(0, 2));

        jLabel2.setText("IP");
        jPanel1.add(jLabel2);

        jTextField1.setText("127.0.0.1");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        jPanel1.add(jTextField1);

        jLabel9.setText("Puerto Serie:");
        jPanel1.add(jLabel9);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8" }));
        jComboBox1.setSelectedIndex(4);
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });
        jPanel1.add(jComboBox1);

        jLabel1.setText("Timeout (ms):");
        jPanel1.add(jLabel1);

        jTextFieldTimeOut.setText("1000");
        jPanel1.add(jTextFieldTimeOut);

        jLabel3.setText("Cantidad de Reintentos:");
        jPanel1.add(jLabel3);

        jTextFieldCantidadDeReintentos.setText("0");
        jPanel1.add(jTextFieldCantidadDeReintentos);

        jLabel4.setText("ID de Dispositivo:");
        jPanel1.add(jLabel4);

        idDispositivoJTextField.setText("1");
        idDispositivoJTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                idDispositivoJTextFieldActionPerformed(evt);
            }
        });
        jPanel1.add(idDispositivoJTextField);

        jLabel7.setText("Función Seleccionada:");
        jPanel1.add(jLabel7);

        jComboBoxFuncion.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "03", "06", "16" }));
        jComboBoxFuncion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxFuncionActionPerformed(evt);
            }
        });
        jPanel1.add(jComboBoxFuncion);

        jLabel5.setText("Dirección Inicial:");
        jPanel1.add(jLabel5);

        jTextFieldDireccionInicial.setText("0");
        jPanel1.add(jTextFieldDireccionInicial);

        jLabel6.setText("Cantidad de Variables:");
        jPanel1.add(jLabel6);

        jTextFieldCantidadDeVariables.setText("1");
        jPanel1.add(jTextFieldCantidadDeVariables);

        jLabel8.setText("Valor/es:");
        jPanel1.add(jLabel8);

        jTextFieldValor.setText("33");
        jPanel1.add(jTextFieldValor);

        buttonGroup1.add(jRadioButton1);
        jRadioButton1.setText("Puerto Serie");

        buttonGroup1.add(jRadioButton2);
        jRadioButton2.setSelected(true);
        jRadioButton2.setText("TCP/IP");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jRadioButton2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jRadioButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(171, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jRadioButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jRadioButton2)
                .addContainerGap(85, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(360, Short.MAX_VALUE)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(38, 38, 38))
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(332, Short.MAX_VALUE)))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(38, Short.MAX_VALUE))
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        jSplitPane1.setLeftComponent(jPanel3);

        jToolBar1.setRollover(true);

        jButton2.setText("Conectar");
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton2);

        jButton3.setText("Desconectar");
        jButton3.setFocusable(false);
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButton3);

        jButton1.setText("Enviar");
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton1);

        jMenu1.setText("File");

        jMenuItem1.setText("Salir");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 681, Short.MAX_VALUE)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 681, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 536, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBoxFuncionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxFuncionActionPerformed
    }//GEN-LAST:event_jComboBoxFuncionActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    try {
        
        RequestCommand command = null;

        int numeroDeFuncion = Integer.parseInt(jComboBoxFuncion.getSelectedItem().toString());
        int numeroDeDispositivo = Integer.parseInt(idDispositivoJTextField.getText());
        int direccion = Integer.parseInt(jTextFieldDireccionInicial.getText());
        int cantidadReintentos = Integer.parseInt(jTextFieldCantidadDeReintentos.getText());
        int timeout = Integer.parseInt(jTextFieldTimeOut.getText());
        
        ConnectionController.timeout = timeout;
        
        switch (numeroDeFuncion) {
            case 3:
                command = new Funcion03RequestCommand(numeroDeDispositivo,
                        direccion,
                        Integer.parseInt(jTextFieldCantidadDeVariables.getText()));

                break;
            case 6:
                command = new Funcion6RequestCommand(numeroDeDispositivo, direccion, Integer.parseInt(jTextFieldValor.getText()));

                break;
            case 16:
                String[] valoresString = jTextFieldValor.getText().split(" ");

                byte[] valores = new byte[valoresString.length * 2];

                byte[] currentValueBytes;

                int i = 0;

                for (String current : valoresString) {
                    if (current != null && !current.isEmpty()) {
                        currentValueBytes = ByteAndConversionsUtils.charToByteArray((char) Integer.parseInt(current));
                        valores[i] = currentValueBytes[0];
                        i++;
                        valores[i] = currentValueBytes[1];
                        i++;
                    }
                }

                command = new Funcion16RequestCommand(numeroDeDispositivo, 
                        direccion, 
                        Integer.parseInt(jTextFieldCantidadDeVariables.getText()), 
                        valores);

                break;
        }

        int i = 0;
        
        while( i <= cantidadReintentos && !command.lecturaExitosa) {

            System.out.println("Inicio Intento: "+i);
            command.ejecutar();
            
            System.out.println("Fin Intento: "+i);
            i++;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}//GEN-LAST:event_jButton1ActionPerformed
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
}//GEN-LAST:event_jComboBox1ActionPerformed

private void idDispositivoJTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_idDispositivoJTextFieldActionPerformed
}//GEN-LAST:event_idDispositivoJTextFieldActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    ConnectionController connectionController;
    
    //TODO , ConnectionController.TIPO_DE_CONECCION_TCP_IP
    if(true){
        connectionController = new TCPConnectionController(502);
    }else{
        connectionController = new SerialConnectionController("com2");//(String) jComboBox1.getSelectedItem()
    }

    connectionController.conectar();
}//GEN-LAST:event_jButton2ActionPerformed

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
    this.dispose();
}//GEN-LAST:event_jMenuItem1ActionPerformed

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PantallaPrincipalUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JTextField idDispositivoJTextField;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBoxFuncion;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextFieldCantidadDeReintentos;
    private javax.swing.JTextField jTextFieldCantidadDeVariables;
    private javax.swing.JTextField jTextFieldDireccionInicial;
    private javax.swing.JTextField jTextFieldTimeOut;
    private javax.swing.JTextField jTextFieldValor;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration//GEN-END:variables

    public void actualizar() {
        jTextArea1.setText(Observador.getInstance().getConsola().toString());
    }
}
